package com.nq.controller.protol;


import com.google.common.collect.Maps;
import com.nq.annotation.RepeatSubmit;
import com.nq.common.ServerResponse;
import com.nq.config.SysInternPool;
import com.nq.pojo.User;
import com.nq.pojo.UserStockSubscribe;
import com.nq.service.*;
import com.nq.utils.PropertiesUtil;

import java.math.BigDecimal;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping({"/user/"})
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    IUserService iUserService;

    @Autowired
    IUserPositionService iUserPositionService;

    @Autowired
    IFileUploadService iFileUploadService;

    @Autowired
    IUserIndexPositionService iUserIndexPositionService;

    @Autowired
    IUserFuturesPositionService iUserFuturesPositionService;

    @Autowired
    IUserStockSubscribeService iUserStockSubscribeService;
    @Autowired
    IStockSubscribeService iStockSubscribeService;
    @Autowired
    IUserPendingorderService userPendingorderService;
    @Autowired
    private StFundApplyService stFundApplyService;


    /**
     * 查询收藏股票列表
     * @param changePercent  涨跌幅 0 降序 1 升序
     * @param request
     * @return
     */
    @RequestMapping({"queryOptionList.do"})
    @ResponseBody
    public ServerResponse queryOptionList(@RequestParam("changePercent") String changePercent,
                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                          HttpServletRequest request) {
        return this.iUserService.queryOptionList(changePercent,pageNo, pageSize, request);
    }

    //添加到自选股
    @RequestMapping({"addOption.do"})
    @ResponseBody
    public ServerResponse addOption(@RequestParam("code") String code,
                                    @RequestParam("market") String market,
                                    HttpServletRequest request) {
        return this.iUserService.addOption(code, market, request);
    }

    //删除自选股
    @RequestMapping({"delOption.do"})
    @ResponseBody
    public ServerResponse delOption(@RequestParam("code") String code, HttpServletRequest request) {
        return this.iUserService.delOption(code, request);
    }

    //查询是否是自选股
    @RequestMapping({"isOption.do"})
    @ResponseBody
    public ServerResponse isOption(@RequestParam("code") String code,
                                   @RequestParam("market") String market,
                                   HttpServletRequest request) {
        return this.iUserService.isOption(code, market, request);
    }


    /**
     * 判断是否可购买涨停板
     * @param stockCode
     * @param market
     * @param request
     * @return
     */
    @RequestMapping({"isBuyUp.do"})
    @ResponseBody
    public ServerResponse isBuyUp(@RequestParam("stockCode") String stockCode,
                                   @RequestParam("market") String market,
                                   HttpServletRequest request) {
        return this.iUserPositionService.isBuyUp(stockCode, market, request);
    }

    /**
     * 用户市场股票购买
     * @param stockCode
     * @param market
     * @param buyNum
     * @param buyType
     * @param lever
     * @param profitTarget
     * @param stopTarget
     * @param request
     * @return
     */
    @RequestMapping({"buy.do"})
    @ResponseBody
    @RepeatSubmit
    public ServerResponse buy(@RequestParam("stockCode") String stockCode,
                              @RequestParam("market") String market,
                              @RequestParam("buyNum") Integer buyNum,
                              @RequestParam("buyType") Integer buyType,
                              @RequestParam("lever") Integer lever,
                              @RequestParam("payPwd") String payPwd,
                              @RequestParam(value = "profitTarget",required = false) BigDecimal profitTarget,
                              @RequestParam(value = "stopTarget",required = false) BigDecimal stopTarget,
                              HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.buy(stockCode, market, buyNum, buyType, lever,profitTarget,stopTarget, request, payPwd);
        } catch (Exception e) {
            log.error("用户的订单操作 = {}", e);
        }
        return serverResponse;
    }


    /**
     * 涨停板股票购买
     * @param stockCode
     * @param market
     * @param buyNum
     * @param buyType
     * @param lever
     * @param password 股票密码
     * @param payPwd 支付密码
     * @param profitTarget
     * @param stopTarget
     * @param request
     * @return
     */
    @RequestMapping({"upBuy.do"})
    @ResponseBody
    @RepeatSubmit
    public ServerResponse upBuy(@RequestParam("stockCode") String stockCode,
                              @RequestParam("market") String market,
                              @RequestParam("buyNum") Integer buyNum,
                              @RequestParam("buyType") Integer buyType,
                              @RequestParam("lever") Integer lever,
                              @RequestParam("password") String password,
                              @RequestParam("payPwd") String payPwd,
                              @RequestParam(value = "profitTarget",required = false) BigDecimal profitTarget,
                              @RequestParam(value = "stopTarget",required = false) BigDecimal stopTarget,
                              HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.upBuy(stockCode, market, buyNum, buyType, lever,profitTarget,stopTarget, password, request, payPwd);
        } catch (Exception e) {
            log.error("User's order operation = {}", e);
        }
        return serverResponse;
    }


    /**
     * 大宗股票购买
     * @param id
     * @param buyNum
     * @param password
     * @param payPwd
     * @param request
     * @return
     */
    @RequestMapping({"dzBuy.do"})
    @ResponseBody
    @RepeatSubmit
    public ServerResponse dzBuy(@RequestParam("id") Integer id,
                                @RequestParam("password") String password,
                                @RequestParam("buyNum") Integer buyNum,
                                @RequestParam("payPwd") String payPwd,
                                HttpServletRequest request) {
        User refreshUser = iUserService.getCurrentRefreshUser(request);
        Integer userId = refreshUser.getId();
        // 同一用户同一时间只能购买一个股票
        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            return this.iUserPositionService.dzBuy(id, password, buyNum, request, payPwd);
        }
    }

    //修改涨跌板
    @RequestMapping({"updateProfitTarget.do"})
    @ResponseBody
    public ServerResponse updateProfitTarget(@RequestParam("positionSn") String positionSn, @RequestParam(value = "profitTarget",required = false) Integer profitTarget,@RequestParam(value = "stopTarget",required = false) Integer stopTarget, HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.updateProfitTarget(positionSn, profitTarget, stopTarget,request);
        } catch (Exception e) {
            log.error("Modify the operation of rising and falling boards = {}", e);
        }
        return serverResponse;
    }

    /**
     * 持仓/挂单卖出
     * @param stockCode
     * @param sellNum
     * @return
     */
    @RequestMapping({"sellNew.do"})
    @ResponseBody
    @RepeatSubmit
    public ServerResponse sellNew(@RequestParam("stockCode") String stockCode,
                                  @RequestParam("market") String market,
                                  @RequestParam("payPwd") String payPwd,
                                  @RequestParam("sellNum") Integer sellNum,
                                  HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            val user = this.iUserService.getCurrentRefreshUser(request);
            serverResponse = this.iUserPositionService.sellNew(stockCode, market, sellNum, payPwd, user.getId());
        } catch (Exception e) {
            log.error("User pending order operation = {}", e);
        }
        return serverResponse;
    }

    /**
     * 用户平仓接口
     * @param request
     * @param positionSn
     * @return
     */
    @RequestMapping({"sell.do"})
    @ResponseBody
    @RepeatSubmit
    public ServerResponse sell(HttpServletRequest request, @RequestParam("positionSn") String positionSn) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.sell(positionSn, 1);
        } catch (Exception e) {
            log.error("User closing operation = {}", e);
        }
        return serverResponse;
    }

    /**
     * 买入挂单
     * @param request
     * @param stockId
     * @param market
     * @param buyNum
     * @param buyType
     * @param lever
     * @param payPwd
     * @param profitTarget
     * @param stopTarget
     * @param targetPrice
     * @return
     */
    @RequestMapping({"addOrder.do"})
    @ResponseBody
    public ServerResponse addOrder(HttpServletRequest request,
                                   @RequestParam("stockId") String stockId,
                                   @RequestParam("market") String market,
                                   @RequestParam("buyNum") Integer buyNum,
                                   @RequestParam("buyType") Integer buyType,
                                   @RequestParam("lever") Integer lever,
                                   @RequestParam("payPwd") String payPwd,
                                   @RequestParam(value = "profitTarget",required = false) BigDecimal profitTarget,
                                   @RequestParam(value = "stopTarget",required = false) BigDecimal stopTarget,
                                   @RequestParam(value = "targetPrice",required = false) BigDecimal targetPrice) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.userPendingorderService.addOrder(stockId, market, buyNum, buyType, lever, profitTarget, stopTarget, targetPrice, request, payPwd);
        } catch (Exception e) {
            log.error("Pending Order Operation - Add = {}", e);
        }
        return serverResponse;
    }

    /**
     * 挂单操作-列表
     * @param request
     * @return
     */
    @RequestMapping({"orderList.do"})
    @ResponseBody
    public ServerResponse orderList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                    HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {

            serverResponse = this.userPendingorderService.orderList(request);
        } catch (Exception e) {
            log.error("Punging Order Operation - List = {}", e);
        }
        return serverResponse;
    }

    //挂单操作-删除
    @RequestMapping({"delOrder.do"})
    @ResponseBody
    public ServerResponse delOrder(HttpServletRequest request, @RequestParam("id") Integer id) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.userPendingorderService.delOrder(id, request);
        } catch (Exception e) {
            log.error("Peding Order Operation - Delete = {}", e);
        }
        return serverResponse;
    }


    /**
     * 卖出挂单
     * @param request
     * @param stockCode
     * @param sellNum
     * @param lever
     * @param targetPrice
     * @return
     */
    @RequestMapping({"sellOutOrder.do"})
    @ResponseBody
    public ServerResponse sellOutOrder(HttpServletRequest request,
                                       @RequestParam("market") String market,
                                       @RequestParam("stockCode") String stockCode,
                                       @RequestParam("sellNum") Integer sellNum,
                                       @RequestParam(value = "lever",required = false) Integer lever,
                                       @RequestParam(value = "targetPrice",required = false) BigDecimal targetPrice) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.userPendingorderService.sellOutOrder(market, stockCode, sellNum, lever, targetPrice, request);
        } catch (Exception e) {
            log.error("Pending Order Operation - Add = {}", e);
        }
        return serverResponse;
    }

    //用户追加保证金操作
    @RequestMapping({"addmargin.do"})
    @ResponseBody
    public ServerResponse addmargin(HttpServletRequest request, @RequestParam("positionSn") String positionSn, @RequestParam("marginAdd") BigDecimal marginAdd) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.addmargin(positionSn, 1, marginAdd);
        } catch (Exception e) {
            log.error("User closing operation = {}", e);
        }
        return serverResponse;
    }


    @RequestMapping({"buyIndex.do"})
    @ResponseBody
    public ServerResponse buyIndex(@RequestParam("indexId") Integer indexId, @RequestParam("buyNum") Integer buyNum, @RequestParam("buyType") Integer buyType, @RequestParam("lever") Integer lever,@RequestParam(value = "profitTarget",required = false) BigDecimal profitTarget,@RequestParam(value = "stopTarget",required = false) BigDecimal stopTarget, HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserIndexPositionService.buyIndex(indexId, buyNum, buyType, lever,profitTarget,stopTarget, request);
        } catch (Exception e) {
            log.error("User's order index operation = {}", e);
        }
        return serverResponse;
    }

    @RequestMapping({"sellIndex.do"})
    @ResponseBody
    public ServerResponse sellIndex(HttpServletRequest request, @RequestParam("positionSn") String positionSn) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserIndexPositionService.sellIndex(positionSn, 1);
        } catch (Exception e) {
            log.error("User closing index operation = {}", e);
        }
        return serverResponse;
    }

    //期货交易 用户下单
    @RequestMapping({"buyFutures.do"})
    @ResponseBody
    public ServerResponse buyFutures(@RequestParam("FuturesId") Integer FuturesId, @RequestParam("buyNum") Integer buyNum, @RequestParam("buyType") Integer buyType, @RequestParam("lever") Integer lever, HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserFuturesPositionService.buyFutures(FuturesId, buyNum, buyType, lever, request);
        } catch (Exception e) {
            log.error("User order futures operation = {}", e);
        }
        return serverResponse;
    }

    @RequestMapping({"sellFutures.do"})
    @ResponseBody
    public ServerResponse sellFutures(HttpServletRequest request, @RequestParam("positionSn") String positionSn) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserFuturesPositionService.sellFutures(positionSn, 1);
        } catch (Exception e) {
            log.error("User closing futures operation = {}", e);
        }
        return serverResponse;
    }

    //查询 用户信息 包含计算账户盈亏
    @RequestMapping({"getUserInfo.do"})
    @ResponseBody
    public ServerResponse getUserInfo(HttpServletRequest request) {
        return this.iUserService.getUserInfo(request);
    }

    //查询 用户等级
    @RequestMapping({"getUserLevel.do"})
    @ResponseBody
    public ServerResponse getUserLevel(HttpServletRequest request) {
        return this.iUserService.getUserLevel(request);
    }

    //修改用户密码
    @RequestMapping({"updatePwd.do"})
    @ResponseBody
    public ServerResponse updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        return this.iUserService.updatePwd(oldPwd, newPwd, request);
    }


    @RequestMapping({"updateUserInfo.do"})
    @ResponseBody
    public ServerResponse updateUserInfo(@RequestParam(value = "code") String code,
                                         @RequestParam("phone") String phone,
                                         @RequestParam("email") String email,
                                         @RequestParam("nickName") String nickName,
                                         @RequestParam("headImg") String headImg,
                                         HttpServletRequest request) {
        return this.iUserService.updateUserInfo(code, phone, email, nickName, headImg, request);
    }

    @RequestMapping({"findIdWithPwd.do"})
    @ResponseBody
    public ServerResponse findIdWithPwd(@RequestParam("phone") String phone){
        return this.iUserService.findIdWithPwd(phone);
    }

    @RequestMapping({"insertWithPwd.do"})
    @ResponseBody
    public ServerResponse insertWithPwd(@RequestParam("with_pwd") String with_pwd,@RequestParam("phone") String phone){
        return this.iUserService.updateWithPwd(with_pwd,phone);
    }


    /**
     * 实名认证申请
     * @param realName
     * @param idCard
     * @param img1key
     * @param img2key
     * @param img3key
     * @param request
     * @return
     */
    @RequestMapping({"auth.do"})
    @ResponseBody
    public ServerResponse auth(String realName, String idCard, String img1key, String img2key, String img3key, HttpServletRequest request) {
        return this.iUserService.auth(realName, idCard, img1key, img2key, img3key, request);
    }

    //图片上传
    @RequestMapping({"upload.do"})
    @ResponseBody
    public ServerResponse upload(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");

        ServerResponse serverResponse = this.iFileUploadService.upload(file, path);
        if (serverResponse.isSuccess()) {
            String targetFileName = serverResponse.getData().toString();
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;


            Map fileMap = Maps.newHashMap();
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);

            return ServerResponse.createBySuccess(fileMap);
        }
        return serverResponse;
    }

    //资产互转
    @RequestMapping({"transAmt.do"})
    @ResponseBody
    public ServerResponse transAmt(@RequestParam("amt") Integer amt, @RequestParam("type") Integer type, HttpServletRequest request) {
        return this.iUserService.transAmt(amt, type, request);
    }

    /**
     * 新股列表
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    @RequestMapping({"stockSubscribeList.do"})
    @ResponseBody
    public ServerResponse stockSubscribeList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                             HttpServletRequest request) {
        return this.iStockSubscribeService.stockSubscribeList(pageNum, pageSize, request);
    }
    /**
     * 新股申购 添加
     * @param
     * @return
     */
    @RequestMapping({"addUserPosition.do"})
    @ResponseBody
    public ServerResponse addUserPosition(UserStockSubscribe model,HttpServletRequest request) {
        return this.iUserStockSubscribeService.insert(model,request);
    }

    /*新股申购-用户新股申购数据*/
    @RequestMapping({"getOneSubscribeByUserId.do"})
    @ResponseBody
    public ServerResponse getOneSubscribeByUserId(@RequestParam(value ="type",required = false)String type, HttpServletRequest request) {
        return this.iUserStockSubscribeService.getOneSubscribeByUserId(type,request);
    }


    /**
     * 获取新股购买详情
     * @param id
     * @param request
     * @return
     */
    @RequestMapping({"getSubscribeDetailById.do"})
    @ResponseBody
    public ServerResponse getSubscribeDetailById(@RequestParam(value ="id") Integer id, HttpServletRequest request) {
        return this.iUserStockSubscribeService.getSubscribeDetailById(id,request);
    }


    /**
     * 新股申购 -用户提交金额（认缴操作）
     * @param id
     * @param request
     * @return
     */
    @RequestMapping({"submitSubscribe.do"})
    @ResponseBody
    public ServerResponse userSubmit( @RequestParam("id") Integer id, HttpServletRequest request) {
        return this.iUserStockSubscribeService.userSubmit(id,request);
    }

    /**
     * 持有单个基金详情
     * @param
     * @return
     */
    @RequestMapping({"holdFundPurchaseShare.do"})
    @ResponseBody
    public ServerResponse holdFundPurchaseShare(@RequestParam("orderNumber") String orderNumber, HttpServletRequest request) {
        return this.stFundApplyService.holdFundPurchaseShare(orderNumber, request);
    }

    /**
     * 基金购买 添加
     * @param
     * @return
     */
    @RequestMapping({"buyUserFund.do"})
    @ResponseBody
    public ServerResponse buyUserFund(@RequestParam("fundId") Integer fundId,
                                      @RequestParam("purchaseAmount") String purchaseAmount,
                                      @RequestParam("payPwd") String payPwd,
                                      HttpServletRequest request) {
        return this.stFundApplyService.addUserFund(fundId, purchaseAmount, payPwd, request);
    }

    /**
     * 基金购买 卖出
     * @param
     * @return
     */
    @RequestMapping({"sellUserFund.do"})
    @ResponseBody
    public ServerResponse sellUserFund(@RequestParam("orderNumber") String orderNumber,
                                       @RequestParam("purchaseAmount") String purchaseAmount,
                                       @RequestParam("payPwd") String payPwd,
                                       HttpServletRequest request) {
        return this.stFundApplyService.sellUserFund(orderNumber, purchaseAmount, payPwd, request);
    }

    /**
     * 基金购买卖记录
     * @param
     * @return
     */
    @RequestMapping({"fundTransactionRecords.do"})
    @ResponseBody
    public ServerResponse fundTransactionRecords(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest request) {
        return this.stFundApplyService.fundTransactionRecords(pageNum, pageSize, request);
    }

    /**
     * 基金持仓记录
     * @param
     * @return
     */
    @RequestMapping({"fundPositionRecord.do"})
    @ResponseBody
    public ServerResponse fundPositionRecord(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest request) {
        return this.stFundApplyService.fundPositionRecord(pageNum, pageSize, request);
    }

    /**
     * 基金手续费
     * @param
     * @return
     */
    @RequestMapping({"queryFundServiceCharge.do"})
    @ResponseBody
    public ServerResponse queryFundServiceCharge(@RequestParam("fundId") Integer fundId,
                                             HttpServletRequest request) {
        return this.stFundApplyService.queryFundServiceCharge(fundId, request);
    }

    /**
     * 大宗下单
     */
    @RequestMapping({"buyStockDz.do"})
    @ResponseBody
    public ServerResponse buyDz(@RequestParam("stockCode") String stockCode, @RequestParam("password") String password,@RequestParam("num") Integer num, HttpServletRequest request) throws Exception {
        return this.iUserPositionService.buyDz(stockCode, password, num, request);
    }

    //大宗下单列表
    @RequestMapping({"buyStockDzList.do"})
    @ResponseBody
    public ServerResponse buyStockDzList( HttpServletRequest request) {
        return this.iUserPositionService.buyStockDzList( request);
    }

    /**
     * 新股抢筹 列表
     */
    @RequestMapping({"newStockQc.do"})
    @ResponseBody
    public ServerResponse newStockQc( HttpServletRequest request) {
        return this.iStockSubscribeService.newStockQc( request);
    }
    /**
     * 新股抢筹 下单
     */
    @RequestMapping({"buyNewStockQc.do"})
    @ResponseBody
    public ServerResponse buyNewStockQc(@RequestParam("code") String code,@RequestParam("num")Integer num, HttpServletRequest request) {
        return this.iUserStockSubscribeService.buyNewStockQc(code,num, request);
    }

    /**
     * vip抢筹 （涨停板买入）
     *
     */
    @RequestMapping({"buyVipQc.do"})
    @ResponseBody
    public ServerResponse buyVipQc(@RequestParam("stockCode") String stockCode, @RequestParam("buyNum") Integer buyNum, @RequestParam("buyType") Integer buyType, @RequestParam("lever") Integer lever,@RequestParam(value = "profitTarget",required = false) BigDecimal profitTarget,@RequestParam(value = "stopTarget",required = false) BigDecimal stopTarget, HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.buyVipQc(stockCode, buyNum, buyType, lever,profitTarget,stopTarget, request);
        } catch (Exception e) {
            log.error("Vip rushed to place an order error = {}", e);
        }
        return serverResponse;
    }

}
